<!--  -->
<template>
  <a-modal
    width="80%"
    :title="isHidden ? '编辑研究中心' : '查看研究中心'"
    :visible="updateCenterVisible"
    :footer="null"
    @cancel="handleCancel(0)"
    @ok="clickSaveCenter"
  >
    <!-- 查看研究中心 -->
    <template v-if="!isHidden">
      <a-descriptions title="研究中心基本信息" bordered>
        <a-descriptions-item label="中心编号">{{ formData.researchCenterNo }}</a-descriptions-item>
        <a-descriptions-item label="选择医院">{{ formData.orgName }}</a-descriptions-item>
        <a-descriptions-item label="英文名称">{{ formData.enName }}</a-descriptions-item>
        <a-descriptions-item label="短名称">{{ formData.shortName }}</a-descriptions-item>
        <a-descriptions-item label="选择科室">{{ formData.orgDeptName }}</a-descriptions-item>
        <a-descriptions-item label="中心状态">{{ formData.active | enumValueByKey($const.RESEARCH_CENTER_STATUS) }}</a-descriptions-item>
        <a-descriptions-item label="crc" :span="1">{{ formData.userName }}</a-descriptions-item>
      </a-descriptions>
    </template>
    <!-- 编辑研究中心 -->
    <template v-else>
      <a-descriptions title="研究中心基本信息"></a-descriptions>
      <a-form-model :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="formRules" ref="formRef">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="中心编号" prop="researchCenterNo">
              <a-input v-model="formData.researchCenterNo" placeholder="请输入中心编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="选择医院" prop="orgId">
              <a-select @change="handleHospitalSelect" disabled v-model="formData.orgId" >
                <a-select-option v-for="item in hospitalList" :key="item.id" :value="item.id">{{
                  item.orgName
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="英文名称">
              <a-input v-model="formData.enName" placeholder="请输入英文名称"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="短名称">
              <a-input v-model="formData.shortName" placeholder="请输入短名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="选择科室">
              <a-select
                mode="multiple"
                placeholder="请先选择医院"
                v-model="hospitalListView"
                @change="handleDepartmentChange"
              >
                <a-select-option v-for="item in departmentList" :key="item.id" :value="item.id" :name="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="中心状态">
              <a-select v-model="formData.active" allowClear>
                <a-select-option v-for="item in $const.RESEARCH_CENTER_STATUS" :key="item.value" :value="item.value">{{ item.desc }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="选择crc">
              <a-select
                placeholder="请先选择crc"
                v-model="crcListView"
                @change="handleCrcChange"
              >
                <a-select-option v-for="item in teamCrcList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div v-if="isHidden">
        <a-button type="primary" :loading="submitting" @click="clickSaveCenter">保存研究中心</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import monitor from '@/utils/monitor'
import updateCenterModal from '@/monitor/views/overview/detail/responsible/components/members/updateCenterModal.js'

import { getCenterDetail, updateCenter, getListCrc } from '@/api/overview/member'
import { getOriginationList, listOrgDepts } from '@/api/common'
// import { nextTick } from 'vue/types/umd'

const watch = monitor(updateCenterModal)

export default {
  name: '',
  props: {
    updateCenterVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      formData: {
        // proId: this.$route.query.id,
        proId: null,
        orgId: null,
        active: null,
        enName: '',
        shortName: '',
        researchCenterNo: null
      },
      formRules: {
        orgId: [{ required: true, message: '请选择医院', trigger: 'change' }],
        researchCenterNo: [
          { required: true, message: '请输入中心编号', trigger: 'change' },
          { pattern: /^[0-9a-zA-Z_]{1,}$/, message: '中心编号只能数字和英文' }
        ]
      },
      hospitalList: [],
      departmentList: [],
      teamCrcList: [],
      hospitalListView: [], // 可以多选的科室
      crcListView: [], // 选择的crc
      submitting: false,
      isHidden: true
    }
  },
  created () {
    this.getListCrc()
  },
  methods: watch({
    // 获取crc列表
    getListCrc () {
      getListCrc({ proId: this.$route.query.id }).then(res => {
        this.teamCrcList = res
      })
      .catch(() => {})
    },
    // 获取中心详情
    getCenterDetail (val) {
      getCenterDetail({ resId: val })
        .then(res => {
          this.formData = res
          this.hospitalListView = res.orgDeptId ? res.orgDeptId.split(',').map(Number) : []
          console.log(this.hospitalListView, '****************')
          if (res.teamIdP) {
            this.crcListView = res.teamIdP.split(',').map(Number)
          } else {
            this.crcListView = []
          }
          this.getHospitalList()
          this.listOrgDepts(res.orgId)
        })
        .catch(() => {})
    },
    // 请求医院列表
    getHospitalList () {
      getOriginationList()
        .then(res => {
          this.hospitalList = res.filter(item => parseInt(item.type) === 2) // 获取的列表中type值为2的是医院
        })
        .catch((err) => {
          console.log('获取的医院列表错误', err)
        })
    },
    // 请求科室列表
    listOrgDepts (val) {
      listOrgDepts({ orgId: val })
        .then(res => {
          this.departmentList = res
        })
        .catch(() => {})
    },
    // 医院选择下拉改变
    handleHospitalSelect (val) {
      if (val) {
        this.formData.orgId = val
        this.listOrgDepts(val)
      } else {
        this.formData.orgId = ''
        this.formData.enName = ''
        this.formData.shortName = ''
        this.departmentList = []
      }

      this.formData.orgDeptId = [] // 将此前选的科室清空
      this.hospitalListView = []
    },
    // 科室选择改变
    handleDepartmentChange (value, option) {
      this.formData.orgDeptId = value
    },
    handleCrcChange (value) {
      this.formData.teamIdP = value
    },
    // 点击保存研究中心
    clickSaveCenter () {
      this.$refs.formRef.validate(valid => {
        if (!valid) {
          this.$message.error('必选项未填写完整')
          return false
        }
        const { id, researchCenterNo, orgId, enName, shortName, active, proId } = { ...this.formData }
        const commitData = { id, researchCenterNo, orgId, enName, shortName, active, proId }
        if (this.hospitalListView) {
          commitData.orgDeptId = JSON.parse(JSON.stringify(this.hospitalListView)).toString()
          console.log(commitData, '...........')
          commitData.orgDeptName = this.departmentList.filter(item => commitData.orgDeptId.indexOf(item.id) >= 0).map(item => item.name).join()
        }
        if (this.formData.teamIdP) {
          commitData.teamIdP = this.formData.teamIdP.toString()
        } else {
          delete commitData.teamIdP
        }
        this.submitting = true
        // 若未选活跃状态 则解构时将active字段过滤了 故需补上
        if (!commitData.active) {
          commitData.active = ''
        }
        updateCenter({ ...commitData })
          .then(res => {
            this.submitting = false
            this.$message.success('研究中心修改成功')
            this.handleCancel(1)
          })
          .catch(() => {
            this.submitting = false
          })
      })
    },
    handleCancel (val) {
      this.$emit('closeUpdateModal', val)
      this.resetForm()
    },
    // 去除校验，重置表单
    resetForm () {
      this.$refs.formRef.resetFields()
      this.hospitalListView = []
      this.crcListView = []
      this.formData = this.$options.data().formData
    }
  })
}
</script>
<style scoped lang="less">
.title {
  line-height: 32px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
  font-size: 16px;
}
</style>
